import React, {
    useState,
    useEffect,
    useMemo,
    Fragment,
    createContext,
} from 'react';
import { Table, Tree, Dropdown, Menu, Checkbox, Tooltip } from 'antd';
import { Resizable } from 'react-resizable';
import { SettingOutlined, FilterOutlined } from '@ant-design/icons';
import { HcpColumnsFilter, HcpColumnsRateFilter } from '@/components';
import moment from 'moment';

// 定义表头筛选重置的Context
export const HcpTableContext = createContext(0);

const ResizeableTitle = (props) => {
    const { onResize, width, ...restProps } = props;

    if (!width) {
        return <th {...restProps} />;
    }

    const resizeHandle = (resizeHandle) => (
        <span
            className={`react-resizable-handle react-resizable-handle-${resizeHandle}`}
            onClick={(e) => {
                e.stopPropagation();
            }}
        />
    );

    return (
        <Resizable
            width={width}
            height={0}
            handle={React.createElement('span', {
                className: `react-resizable-handle`,
                onClick: (e) => {
                    e.stopPropagation();
                },
            })}
            onResize={onResize}
            draggableOpts={{ enableUserSelectHack: false }}
        >
            <th {...restProps} />
        </Resizable>
    );
};

const HcpTable = (props) => {
    // useCountRenders();

    const {
        columns: initialColumns,
        bordered,
        loading,
        dataSource,
        locale,
        rowSelection,
        scroll,
        pagination,
        onChange,
        hideSetting,
        noSorter,
        expandedRowRender,
        expandIcon,
        onExpand,
        onExpandedRowsChange,
        expandedRowKeys,
        regionSource,
        cloudsSource,
        azsSource,
        statusSource,
        projectSource,
        rangeFilter,
        handleFilters,
        status,
        backUpsStatusSource,
        colReset,
        rowKey,
        settingData,
        settingSelectKeys,
        className,
        ...prop
    } = props;
    const handleResize =
        (index) =>
            (e, { size }) => {
                setColumns((columns) => {
                    const nextColumns = [...columns];
                    nextColumns[index] = {
                        ...nextColumns[index],
                        width: size.width,
                    };
                    return nextColumns;
                });
            };
    const [selectKeys, setSelectKeys] = useState([]);

    const onCheck = (checkedObj, info) => {
        let keys = checkedObj.checked;
        let posArr = info.node.pos.split('-');
        if (posArr.length === 2) {
            if (info.node.children?.length) {
                // 一级节点
                info.node.children.forEach((childNode) => {
                    let index = keys.findIndex((key) => {
                        return childNode.dataIndex === key;
                    });
                    if (info.node.checked) {
                        if (index !== -1) {
                            keys.splice(index, 1);
                        }
                    } else if (index === -1) {
                        keys.push(childNode.dataIndex);
                    }
                });
            }
        } else if (posArr.length === 3) {
            // 二级节点, 选中时看父节点是否选中，若无则选中
            if (settingData && settingData.length) {
                let parentNode = settingData[Number(posArr[1])];
                let index = keys.findIndex((key) => {
                    return key === parentNode?.dataIndex;
                });
                if (index == -1) {
                    keys.push(parentNode?.dataIndex);
                }
            }
        }
        setSelectKeys(keys);
    };

    // 返回类型默认为表格筛选属性
    const onChangeRegion = (item, key) => {
        if (handleFilters) handleFilters(key || 'regionCode', item);
    };
    const onChangeCloud = (item, key) => {
        if (handleFilters) handleFilters(key || 'cloudCode', item);
    };
    const onChangeAzs = (item, key) => {
        if (handleFilters) handleFilters(key || 'azCode', item);
    };
    const onChangeStatus = (item) => {
        if (handleFilters) handleFilters('status', item);
    };
    const onChangeProject = (item) => {
        if (handleFilters) handleFilters('projectId', item);
    };
    const onChangeRate = (item) => {
        console.log(item);
    };

    let selectedKeys = settingSelectKeys || [];

    useEffect(() => {
        initColumns();
    }, []);

    function initColumns() {
        initialColumns.map((col, index) => {
            if (col.title) {
                col.width = col.width || 150;
                if (col.sorter) {
                    col.sorter = (a, b) => {
                        if (col.sorterApi) return;
                        let c = isFinite(a[col.dataIndex]);
                        let d = isFinite(b[col.dataIndex]);
                        if (c && d) {
                            return a[col.dataIndex] - b[col.dataIndex];
                        } else if (col.sorterCN) {
                            // 名称排序
                            return a.instanceName.localeCompare(b.instanceName);
                        } else {
                            return (
                                a[col.dataIndex].length -
                                b[col.dataIndex].length
                            );
                        }
                    };
                } else {
                    col.sorter = false;
                }
                col.ellipsis = true;
            }
            if (col.isShow == undefined) col.isShow = true;
            if (!col.align) col.align = 'center';
            if (!col.key) col.key = col.dataIndex;
            col.onHeaderCell = (column) => {
                return {
                    width: column.width,
                    onResize: handleResize(index),
                };
            };

            if (!col.render && col.type !== 'time') {
                col.render = (value) => {
                    if (value === 0) return 0;
                    return value || '-';
                };
            }

            if (col.type == 'time') {
                col.render = (value) => {
                    value = Number.isNaN(Number(value)) ? value : Number(value);
                    return value
                        ? moment(value).format(col.timeFormat || 'YYYY-MM-DD HH:mm:ss')
                        : '-';
                };
            }

            if (col.type == 'status') {
                if (status) {
                    col.render = (value) => status[value];
                }
            }

            if (col.type == 'Boolean') {
                col.render = (value) => {
                    return value == 'true' ? '是' : '否';
                };
            }
            // 增加tooltip,属性就可以开启tooltip (如果render中return <> tooltip会失效，暂时还不知道原因)
            if (col.tooltip) {
                let tmp = col.render;
                col.render = (text, record, index) => {
                    return (
                        <Tooltip
                            placement="top"
                            title={tmp(text, record, index)}
                        >
                            <span className="block_span_nowrap" >{tmp(text, record, index)}</span>
                        </Tooltip>
                    );
                };
            }

            if (col.alwaysShow) {
                col.isShow = true;
                col.disabled = true;
            }

            if (col.customSorter) {
                col.sorter = col.customSorter;
            }

        });
        if (!selectedKeys.length) {
            initialColumns.map((col, index) => {
                if (index == 0) {
                    col.alwaysShow = true;
                }
                if (col.isShow === true) {
                    selectedKeys.push(col.key);
                }
            });
        }
        if (noSorter) {
            initialColumns.map((col) => {
                col.sorter = null;
            });
        }
        setSelectKeys(selectedKeys);
    }
    const [columns, setColumns] = useState(initialColumns);
    useEffect(() => {
        setColumns((columns) => {
            columns = columns.filter(
                (col) => !col.type || col.type != 'hcp__table__setting'
            );
            columns = columns.map((col) => {
                col.isShow = false;
                selectKeys.map((item) => {
                    if (col.key == item) col.isShow = true;
                });
                return col;
            });
            // 组合列增加边框
            if (settingData && settingData.length) {
                settingData.forEach((col) => {
                    let childHasSelect = false;
                    let lastChildColumnIndex = 0;
                    if (col.children && col.children.length) {
                        col.children.forEach((item) => {
                            let keyIndex = selectKeys.findIndex(
                                (key) => key === item.dataIndex
                            );
                            if (keyIndex !== -1) {
                                childHasSelect = true;
                                let columnRealIndex = columns.findIndex(
                                    (column) =>
                                        column.dataIndex ===
                                        selectKeys[keyIndex]
                                );
                                if (columnRealIndex > lastChildColumnIndex)
                                    lastChildColumnIndex = columnRealIndex;
                                Object.assign(columns[columnRealIndex], {
                                    onCell: () => {
                                        return {};
                                    },
                                });
                            }
                        });
                    }
                    let startRealIndex = columns.findIndex(
                        (column) => column.dataIndex === col.dataIndex
                    );
                    if (childHasSelect && lastChildColumnIndex) {
                        Object.assign(columns[startRealIndex], {
                            onCell: () => {
                                return { className: 'column-border-left' };
                            },
                        });
                        Object.assign(columns[lastChildColumnIndex], {
                            onCell: () => {
                                return { className: 'column-border-right' };
                            },
                        });
                    } else {
                        Object.assign(columns[startRealIndex], {
                            onCell: () => {
                                return {};
                            },
                        });
                    }
                });
            }
            // settings
            let cols = [];
            columns.forEach((col) => {
                let col_ = Object.assign({}, col);
                if (col_.filtersType) col_.title = col_.title?.props?.name;
                cols.push(col_);
            });
            let treeData = settingData || cols;
            let settingCol = {
                type: 'hcp__table__setting',
                isShow: true,
                fixed: 'right',
                width: 50,
                className: 'hcp__table__setting',
                filterDropdown: ({ confirm, clearFilters }) => (
                    <div style={{ padding: 8 }}>
                        <Tree
                            checkable
                            defaultExpandAll
                            checkStrictly
                            selectable={false}
                            onCheck={onCheck}
                            treeData={treeData}
                            checkedKeys={selectKeys}
                        />
                    </div>
                ),
                filterIcon: (filtered) => <SettingOutlined />,
            };
            if (!hideSetting) columns.push(settingCol);
            return [...columns];
        });
    }, [selectKeys]);

    // initColumns改变后,重新整理columns,以及下面的多个effect,重新渲染可搜索的列
    useEffect(() => {
        if (initialColumns) {
            setColumns(initialColumns);
            initColumns();
        }
    }, [initialColumns]);

    useEffect(() => {
        setColumns((columns) => {
            columns.map((col) => {
                col.title = col.filtersType === 'region' ? (
                    <HcpColumnsFilter
                        name="资源池"
                        dataSource={regionSource}
                        handleChange={e => { onChangeRegion(e, col.filtersTypeKey) }}
                    />
                ) : col.title;
            });
            return [...columns];
        });
    }, [regionSource, initialColumns]);

    useEffect(() => {
        setColumns((columns) => {
            columns.map((col) => {
                col.title = col.filtersType === 'cloud' || col.filtersType === 'cloudIds' ? (
                    <HcpColumnsFilter
                        name="云服务商"
                        dataSource={cloudsSource}
                        filtersType={col.filtersType}
                        handleChange={(e) => { onChangeCloud(e, col.filtersTypeKey) }}
                    />
                ) : col.title;
            });
            return [...columns];
        });
    }, [cloudsSource, initialColumns]);
    useEffect(() => {
        setColumns((columns) => {
            columns.map((col) => {
                col.title = col.filtersType === 'az' ? (
                    <HcpColumnsFilter
                        name="可用域"
                        dataSource={azsSource}
                        filtersType={col.filtersType}
                        handleChange={(e) => { onChangeAzs(e, col.filtersTypeKey) }}
                    />
                ) : col.title;
            });
            return [...columns];
        });
    }, [azsSource, initialColumns]);
    useEffect(() => {
        if (rangeFilter) {
            setColumns((columns) => {
                columns.map((col) => {
                    let index = rangeFilter.findIndex((item) => {
                        return item.dataIndex === col.dataIndex;
                    });
                    (col.filterIcon = (filtered) => (
                        <SearchOutlined
                            style={{ color: filtered ? '#1890ff' : undefined }}
                        />
                    )),
                        col.title = index !== -1 ? (
                            <HcpColumnsRateFilter
                                filterInfo={rangeFilter[index]}
                                handleChange={onChangeRate}
                            />
                        ) : col.title;
                });
                return [...columns];
            });
        }
    }, [rangeFilter, initialColumns]);

    useEffect(() => {
        setColumns((columns) => {
            columns.map((col) => {
                col.title = col.filtersType === 'project' ? (
                    <HcpColumnsFilter
                        name="项目"
                        dataSource={projectSource}
                        handleChange={onChangeProject}
                    />
                ) : col.title;
            });
            return [...columns];
        });
    }, [projectSource, initialColumns]);

    useEffect(() => {
        setColumns((columns) => {
            columns.map((col) => {
                col.title = col.filtersType === 'status' ? (
                    <HcpColumnsFilter
                        name="状态"
                        dataSource={statusSource}
                        handleChange={onChangeStatus}
                    />
                ) : col.title;
            });

            return [...columns];
        });
    }, [statusSource, initialColumns]);

    useEffect(() => {
        setColumns((columns) => {
            columns.map((col) => {
                col.title = col.filtersType === 'backUpsStatus' ? (
                    <HcpColumnsFilter
                        name="状态"
                        dataSource={backUpsStatusSource}
                        handleChange={onChangeStatus}
                    />
                ) : col.title;
            });
            return [...columns];
        });
    }, [statusSource, initialColumns]);

    const components = {
        header: {
            cell: ResizeableTitle,
        },
    };
    return (
        <HcpTableContext.Provider value={colReset}>
            <Table
                {...prop}
                className={
                    className ? `hcp_clear_both ${className}` : 'hcp_clear_both'
                }
                rowKey={rowKey}
                bordered={bordered}
                expandedRowKeys={expandedRowKeys}
                onExpandedRowsChange={onExpandedRowsChange}
                expandable={{ expandedRowRender, expandIcon }}
                onExpand={onExpand}
                components={components}
                columns={columns.filter((i) => i.isShow)}
                loading={loading}
                dataSource={dataSource}
                locale={locale}
                rowSelection={rowSelection}
                scroll={scroll || { x: '100%' }}
                pagination={pagination}
                onChange={onChange}
                {...prop}
            />
        </HcpTableContext.Provider>
    );
};

export default HcpTable;
